#!/bin/bash

# 工具面板脚本 - SSH端口更改和禁用ping管理
# 作者: System Admin
# 版本: 1.0
# 日期: $(date +%Y-%m-%d)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 日志文件
LOG_FILE="/var/log/tool_panel.log"

# 记录日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# 显示标题
show_title() {
    clear
    echo -e "${CYAN}========================================${NC}"
    echo -e "${CYAN}        系统工具管理面板              ${NC}"
    echo -e "${CYAN}========================================${NC}"
    echo -e "${CYAN}    SSH端口管理 | Ping控制 | 系统工具  ${NC}"
    echo -e "${CYAN}========================================${NC}"
    echo
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误: 此脚本需要root权限运行${NC}"
        echo -e "${YELLOW}请使用: sudo $0${NC}"
        exit 1
    fi
}

# 备份SSH配置
backup_ssh_config() {
    local backup_file="/etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)"
    if cp /etc/ssh/sshd_config "$backup_file"; then
        log_message "SSH配置已备份到: $backup_file"
        echo -e "${GREEN}✓ SSH配置已备份${NC}"
    else
        log_message "SSH配置备份失败"
        echo -e "${RED}✗ SSH配置备份失败${NC}"
        return 1
    fi
}

# 获取当前SSH端口
get_current_ssh_port() {
    local current_port=$(grep -E "^Port\s+" /etc/ssh/sshd_config | awk '{print $2}')
    if [[ -z "$current_port" ]]; then
        echo "22"
    else
        echo "$current_port"
    fi
}

# 更改SSH端口
change_ssh_port() {
    local current_port=$(get_current_ssh_port)
    local new_port
    
    echo -e "${YELLOW}当前SSH端口: $current_port${NC}"
    echo -e "${BLUE}请输入新的SSH端口 (1024-65535):${NC}"
    read -p "新端口: " new_port
    
    # 验证端口号
    if ! [[ "$new_port" =~ ^[0-9]+$ ]] || [ "$new_port" -lt 1024 ] || [ "$new_port" -gt 65535 ]; then
        echo -e "${RED}错误: 端口号必须在1024-65535之间${NC}"
        return 1
    fi
    
    # 检查端口是否被占用
    if netstat -tuln | grep -q ":$new_port "; then
        echo -e "${RED}错误: 端口 $new_port 已被占用${NC}"
        return 1
    fi
    
    # 备份配置
    backup_ssh_config
    
    # 修改SSH配置
    if sed -i "s/^#*Port.*/Port $new_port/" /etc/ssh/sshd_config; then
        log_message "SSH端口已更改为: $new_port"
        echo -e "${GREEN}✓ SSH端口已更改为 $new_port${NC}"
        
        # 重启SSH服务
        echo -e "${YELLOW}正在重启SSH服务...${NC}"
        if systemctl restart sshd; then
            log_message "SSH服务重启成功"
            echo -e "${GREEN}✓ SSH服务重启成功${NC}"
            echo -e "${YELLOW}注意: 请使用新端口 $new_port 连接SSH${NC}"
        else
            log_message "SSH服务重启失败"
            echo -e "${RED}✗ SSH服务重启失败${NC}"
            return 1
        fi
    else
        log_message "SSH端口更改失败"
        echo -e "${RED}✗ SSH端口更改失败${NC}"
        return 1
    fi
}

# 检查ping状态
check_ping_status() {
    if sysctl -n net.ipv4.icmp_echo_ignore_all 2>/dev/null | grep -q "1"; then
        echo "disabled"
    else
        echo "enabled"
    fi
}

# 禁用ping
disable_ping() {
    local current_status=$(check_ping_status)
    
    if [[ "$current_status" == "disabled" ]]; then
        echo -e "${YELLOW}Ping已经处于禁用状态${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}正在禁用ping...${NC}"
    
    # 临时禁用
    if sysctl -w net.ipv4.icmp_echo_ignore_all=1; then
        log_message "Ping已临时禁用"
        echo -e "${GREEN}✓ Ping已临时禁用${NC}"
    else
        log_message "Ping临时禁用失败"
        echo -e "${RED}✗ Ping临时禁用失败${NC}"
        return 1
    fi
    
    # 永久禁用
    if ! grep -q "net.ipv4.icmp_echo_ignore_all" /etc/sysctl.conf; then
        echo "net.ipv4.icmp_echo_ignore_all = 1" >> /etc/sysctl.conf
    else
        sed -i 's/^#*net\.ipv4\.icmp_echo_ignore_all.*/net.ipv4.icmp_echo_ignore_all = 1/' /etc/sysctl.conf
    fi
    
    # 应用配置
    if sysctl -p; then
        log_message "Ping永久禁用配置已应用"
        echo -e "${GREEN}✓ Ping永久禁用配置已应用${NC}"
    else
        log_message "Ping永久禁用配置应用失败"
        echo -e "${RED}✗ Ping永久禁用配置应用失败${NC}"
        return 1
    fi
}

# 启用ping
enable_ping() {
    local current_status=$(check_ping_status)
    
    if [[ "$current_status" == "enabled" ]]; then
        echo -e "${YELLOW}Ping已经处于启用状态${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}正在启用ping...${NC}"
    
    # 临时启用
    if sysctl -w net.ipv4.icmp_echo_ignore_all=0; then
        log_message "Ping已临时启用"
        echo -e "${GREEN}✓ Ping已临时启用${NC}"
    else
        log_message "Ping临时启用失败"
        echo -e "${RED}✗ Ping临时启用失败${NC}"
        return 1
    fi
    
    # 永久启用
    if ! grep -q "net.ipv4.icmp_echo_ignore_all" /etc/sysctl.conf; then
        echo "net.ipv4.icmp_echo_ignore_all = 0" >> /etc/sysctl.conf
    else
        sed -i 's/^#*net\.ipv4\.icmp_echo_ignore_all.*/net.ipv4.icmp_echo_ignore_all = 0/' /etc/sysctl.conf
    fi
    
    # 应用配置
    if sysctl -p; then
        log_message "Ping永久启用配置已应用"
        echo -e "${GREEN}✓ Ping永久启用配置已应用${NC}"
    else
        log_message "Ping永久启用配置应用失败"
        echo -e "${RED}✗ Ping永久启用配置应用失败${NC}"
        return 1
    fi
}

# 显示系统信息
show_system_info() {
    echo -e "${BLUE}========== 系统信息 ==========${NC}"
    echo -e "${YELLOW}操作系统:${NC} $(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)"
    echo -e "${YELLOW}内核版本:${NC} $(uname -r)"
    echo -e "${YELLOW}主机名:${NC} $(hostname)"
    echo -e "${YELLOW}当前时间:${NC} $(date)"
    echo -e "${YELLOW}运行时间:${NC} $(uptime -p)"
    echo -e "${YELLOW}内存使用:${NC} $(free -h | grep Mem | awk '{print $3"/"$2}')"
    echo -e "${YELLOW}磁盘使用:${NC} $(df -h / | tail -1 | awk '{print $5}')"
    echo
}

# 显示网络状态
show_network_status() {
    echo -e "${BLUE}========== 网络状态 ==========${NC}"
    echo -e "${YELLOW}SSH端口:${NC} $(get_current_ssh_port)"
    echo -e "${YELLOW}Ping状态:${NC} $(check_ping_status)"
    echo -e "${YELLOW}SSH服务状态:${NC} $(systemctl is-active sshd)"
    echo -e "${YELLOW}防火墙状态:${NC} $(systemctl is-active firewalld 2>/dev/null || echo "未安装")"
    echo
}

# 防火墙管理
manage_firewall() {
    echo -e "${BLUE}========== 防火墙管理 ==========${NC}"
    echo "1. 查看防火墙状态"
    echo "2. 启动防火墙"
    echo "3. 停止防火墙"
    echo "4. 重启防火墙"
    echo "5. 查看防火墙规则"
    echo "0. 返回主菜单"
    echo
    read -p "请选择操作: " choice
    
    case $choice in
        1)
            systemctl status firewalld
            ;;
        2)
            systemctl start firewalld
            systemctl enable firewalld
            echo -e "${GREEN}防火墙已启动并设置为开机自启${NC}"
            ;;
        3)
            systemctl stop firewalld
            systemctl disable firewalld
            echo -e "${YELLOW}防火墙已停止并禁用开机自启${NC}"
            ;;
        4)
            systemctl restart firewalld
            echo -e "${GREEN}防火墙已重启${NC}"
            ;;
        5)
            firewall-cmd --list-all
            ;;
        0)
            return
            ;;
        *)
            echo -e "${RED}无效选择${NC}"
            ;;
    esac
    
    read -p "按回车键继续..."
}

# 系统服务管理
manage_services() {
    echo -e "${BLUE}========== 系统服务管理 ==========${NC}"
    echo "1. 查看SSH服务状态"
    echo "2. 重启SSH服务"
    echo "3. 查看所有服务状态"
    echo "4. 查看系统日志"
    echo "0. 返回主菜单"
    echo
    read -p "请选择操作: " choice
    
    case $choice in
        1)
            systemctl status sshd
            ;;
        2)
            systemctl restart sshd
            echo -e "${GREEN}SSH服务已重启${NC}"
            ;;
        3)
            systemctl list-units --type=service --state=running
            ;;
        4)
            journalctl -f -n 50
            ;;
        0)
            return
            ;;
        *)
            echo -e "${RED}无效选择${NC}"
            ;;
    esac
    
    read -p "按回车键继续..."
}

# 主菜单
main_menu() {
    while true; do
        show_title
        show_system_info
        show_network_status
        
        echo -e "${BLUE}========== 主菜单 ==========${NC}"
        echo "1. SSH端口管理"
        echo "2. Ping控制"
        echo "3. 防火墙管理"
        echo "4. 系统服务管理"
        echo "5. 查看日志"
        echo "0. 退出"
        echo
        read -p "请选择操作: " choice
        echo
        
        case $choice in
            1)
                ssh_port_menu
                ;;
            2)
                ping_control_menu
                ;;
            3)
                manage_firewall
                ;;
            4)
                manage_services
                ;;
            5)
                view_logs
                ;;
            0)
                echo -e "${GREEN}感谢使用系统工具管理面板！${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}无效选择，请重新输入${NC}"
                sleep 2
                ;;
        esac
    done
}

# SSH端口管理菜单
ssh_port_menu() {
    while true; do
        show_title
        echo -e "${BLUE}========== SSH端口管理 ==========${NC}"
        echo "当前SSH端口: $(get_current_ssh_port)"
        echo
        echo "1. 更改SSH端口"
        echo "2. 查看SSH配置"
        echo "3. 测试SSH连接"
        echo "0. 返回主菜单"
        echo
        read -p "请选择操作: " choice
        echo
        
        case $choice in
            1)
                change_ssh_port
                read -p "按回车键继续..."
                ;;
            2)
                echo -e "${YELLOW}SSH配置文件内容:${NC}"
                cat /etc/ssh/sshd_config | grep -E "^(Port|#Port)"
                read -p "按回车键继续..."
                ;;
            3)
                local current_port=$(get_current_ssh_port)
                echo -e "${YELLOW}测试SSH连接 (端口: $current_port)...${NC}"
                if timeout 5 bash -c "</dev/tcp/127.0.0.1/$current_port"; then
                    echo -e "${GREEN}✓ SSH连接正常${NC}"
                else
                    echo -e "${RED}✗ SSH连接失败${NC}"
                fi
                read -p "按回车键继续..."
                ;;
            0)
                return
                ;;
            *)
                echo -e "${RED}无效选择${NC}"
                sleep 2
                ;;
        esac
    done
}

# Ping控制菜单
ping_control_menu() {
    while true; do
        show_title
        echo -e "${BLUE}========== Ping控制 ==========${NC}"
        local ping_status=$(check_ping_status)
        echo "当前Ping状态: $ping_status"
        echo
        echo "1. 禁用Ping"
        echo "2. 启用Ping"
        echo "3. 测试Ping功能"
        echo "0. 返回主菜单"
        echo
        read -p "请选择操作: " choice
        echo
        
        case $choice in
            1)
                disable_ping
                read -p "按回车键继续..."
                ;;
            2)
                enable_ping
                read -p "按回车键继续..."
                ;;
            3)
                echo -e "${YELLOW}测试Ping功能...${NC}"
                if ping -c 3 127.0.0.1 >/dev/null 2>&1; then
                    echo -e "${GREEN}✓ Ping功能正常${NC}"
                else
                    echo -e "${RED}✗ Ping功能被禁用${NC}"
                fi
                read -p "按回车键继续..."
                ;;
            0)
                return
                ;;
            *)
                echo -e "${RED}无效选择${NC}"
                sleep 2
                ;;
        esac
    done
}

# 查看日志
view_logs() {
    echo -e "${BLUE}========== 日志查看 ==========${NC}"
    echo "1. 查看工具面板日志"
    echo "2. 查看SSH日志"
    echo "3. 查看系统日志"
    echo "4. 清空工具面板日志"
    echo "0. 返回主菜单"
    echo
    read -p "请选择操作: " choice
    echo
    
    case $choice in
        1)
            if [[ -f "$LOG_FILE" ]]; then
                tail -f "$LOG_FILE"
            else
                echo -e "${YELLOW}日志文件不存在${NC}"
            fi
            ;;
        2)
            journalctl -u sshd -f
            ;;
        3)
            journalctl -f
            ;;
        4)
            if [[ -f "$LOG_FILE" ]]; then
                > "$LOG_FILE"
                echo -e "${GREEN}日志已清空${NC}"
            else
                echo -e "${YELLOW}日志文件不存在${NC}"
            fi
            ;;
        0)
            return
            ;;
        *)
            echo -e "${RED}无效选择${NC}"
            ;;
    esac
    
    read -p "按回车键继续..."
}

# 脚本入口
main() {
    check_root
    log_message "工具面板启动"
    main_menu
}

# 捕获中断信号
trap 'echo -e "\n${YELLOW}正在退出...${NC}"; log_message "工具面板退出"; exit 0' INT TERM

# 运行主函数
main "$@"
